import time
import requests
from loguru import logger
from orm_info import WeatherInfo,CityInfo

logger.add(sink='runlog_{}.log'.format(time.strftime("%Y%m%d",time.localtime())),
           rotation='50 MB',
           encoding='utf-8',
           level="INFO")

def get_weather_all(citycode):
    userkey="88bbdc96a39b7051525e576b85a1170f"
    url = "https://restapi.amap.com/v3/weather/weatherInfo?city={}&key={}&extensions=all&output=json".format(str(citycode),userkey)
    r = requests.get(url=url)
    logger.debug("地区:{}天气查询结果：{}".format(citycode,r.text))
    try:
        info = r.json()['forecasts'][0]['casts']
        if info != []:
            logger.debug("地区:{}天气查询成功：{}".format(citycode, info))
            return r.json()
        else:
            logger.warning("地区:{}未查到天气".format(citycode))
            return False
    except:
        logger.warning("地区:{}查询天气响应解析错误".format(citycode))
        return False

def process_weatherinfo(weatherinfojson):
    baseweatherinfo = {}
    baseweatherinfo['adcode'] = weatherinfojson['forecasts'][0]['adcode']
    baseweatherinfo['province'] = weatherinfojson['forecasts'][0]['province']
    baseweatherinfo['city'] = weatherinfojson['forecasts'][0]['city']
    baseweatherinfo['reporttime'] = weatherinfojson['forecasts'][0]['reporttime']
    alldayweather = []
    for oneday in weatherinfojson['forecasts'][0]['casts']:
        onedayweather = {}
        onedayweather['date'] = oneday['date']
        onedayweather['dayweather'] = oneday['dayweather']
        onedayweather['nightweather'] = oneday['nightweather']
        onedayweather['daytemp'] = oneday['daytemp']
        onedayweather['nighttemp'] = oneday['nighttemp']
        onedayweather['daywind'] = oneday['daywind']
        onedayweather['nightwind'] = oneday['nightwind']
        onedayweather['daypower'] = oneday['daypower']
        onedayweather['nightpower'] = oneday['nightpower']
        onedayweather.update(baseweatherinfo)
        alldayweather.append(onedayweather)
    return alldayweather

def insert_weather_onecity(citycode):
    r = process_weatherinfo(get_weather_all(citycode))
    WeatherInfo.insert_many(r).execute()
    logger.debug("地区:{}天气写入数据库成功。".format(citycode))

if __name__ == '__main__':
    # rows = CityInfo.select()
    # for row in rows:
    #     try:
    #         insert_weather_onecity(str(row.adcode))
    #         logger.info("地区:{}-地区代码:{}天气写入数据库成功。".format(row.adname,str(row.adcode)))
    #     except:
    #         logger.warning("地区:{}-地区代码:{}天气写入数据库失败。".format(row.adname,str(row.adcode)))

    print(get_weather_all("710000"))



